#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>

#include "qt_windows.h"
#include "dbt.h"

#include "devicenotifier.h"

using namespace Mikroakustika::MDeviceChecker;

Q_CORE_EXPORT HINSTANCE qWinAppInst ();

DeviceNotifier *DeviceNotifier::pInstance = 0;

HWND wnd = 0;

void createWindow ();
LRESULT CALLBACK windowProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
void destroyWindow ();

DeviceNotifier *DeviceNotifier::instance ()
{
    if (!DeviceNotifier::pInstance) {
        pInstance = new DeviceNotifier (QCoreApplication::instance ());
    }

    return pInstance;
}

DeviceNotifier::DeviceNotifier (QObject *parent)
    : QObject (parent)
{
    createWindow ();
}

DeviceNotifier::~DeviceNotifier ()
{
    if (pInstance == this) {
        pInstance = 0;
        destroyWindow ();
    }
}

void createWindow ()
{
    WNDCLASS wc;
    wc.style = 0;
    wc.lpfnWndProc = windowProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = 0;
    wc.hIcon = 0;
    wc.hCursor = 0;
    wc.hbrBackground = 0;
    wc.lpszMenuName = 0;
    wc.lpszClassName = L"DeviceNotifierWindow";

    RegisterClass (&wc);

    wnd = CreateWindow (wc.lpszClassName,
                        wc.lpszClassName,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0);
    if (!wnd) {
        qDebug () << QString ("Error creating DeviceNotifier window %1")
                     .arg (static_cast <int> (GetLastError()));
    }
}

LRESULT CALLBACK windowProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message) {
    case WM_DEVICECHANGE:
        switch (wParam) {
        case DBT_DEVICEARRIVAL:
            QMetaObject::invokeMethod (DeviceNotifier::instance(),
                                       "deviceArrival",
                                       Qt::AutoConnection);
            break;
        case DBT_DEVICEREMOVECOMPLETE:
            QMetaObject::invokeMethod (DeviceNotifier::instance(),
                                       "deviceRemove",
                                       Qt::AutoConnection);
            break;
        }
        break;
    }

    return DefWindowProc (hwnd, message, wParam, lParam);
}

void destroyWindow ()
{
    if (wnd) {
        DestroyWindow (wnd);
    }

    UnregisterClass (L"DeviceNotifierWindow", 0);
}
// kate: indent-mode cstyle; replace-tabs off; tab-width 4; 
